// 事件通信频道
export class EventChannel {
    // 单例
    private static instance: EventChannel
    // 事件中心
    private eventMap: Map<string, Function[]> = new Map()

    private constructor() { }
    // 获取实例
    public static getInstance() {
        if (!EventChannel.instance) {
            EventChannel.instance = new EventChannel()
        }
        return EventChannel.instance
    }
    // 注册事件
    public on(eventName: string, callback: Function) {
        if (!this.eventMap.has(eventName)) {
            this.eventMap.set(eventName, [])
        }
        this.eventMap.get(eventName)?.push(callback)
    }
    // 触发事件
    public emit(eventName: string, ...args: any[]) {
        if (!this.eventMap.has(eventName)) {
            return
        }
        this.eventMap.get(eventName)?.forEach((callback) => {
            callback(...args)
        })
    }
    // 移除事件
    public remove(eventName: string) {
        if (!this.eventMap.has(eventName)) {
            return
        }
        this.eventMap.delete(eventName)
    }
}